<script setup lang="ts">
import {
  getPatientList,
  addPatient,
  editPatinet,
  delPatient
} from '@/services/user'
import type { PatientList } from '@/types/user'
import type { Patient } from '@/types/user'
import { computed } from 'vue'
import { ref, onMounted } from 'vue'
import { idCardRule, nameRules } from '@/utils/rules'
import {
  showConfirmDialog,
  type FormInstance,
  showSuccessToast,
  showToast
} from 'vant'
import { useRoute } from 'vue-router'
import { useConsultStore } from '@/stores'
import router from '@/router'

// 患者列表数据
const list = ref<PatientList>([])

const loadList = async () => {
  const res = await getPatientList()
  list.value = res.data
  // 选择默认患者
  if (isChange.value && list.value.length) {
    const defPatient = list.value.find((item) => item.defaultFlag === 1) //find找到默认选中的第一个对象
    // 如果有默认对象 就把默认对象的id给选中对象patientId
    if (defPatient) patientId.value = defPatient.id
    // 如果没有则选中list里面的第一个对象
    else patientId.value = list.value[0].id
  }
}

onMounted(() => {
  loadList()
})

const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]

const show = ref(false)
const showPopup = (item: Patient) => {
  if (item) {
    // 如果是编辑带有值的话数据回显
    const { id, idCard, name, gender, defaultFlag } = item
    patient.value = { id, idCard, name, gender, defaultFlag }
  } else {
    // 如果是添加的话 重置校验 打开时就清空表单数据
    form.value?.resetValidation()
    patient.value = { ...initPatient }
  }
  show.value = true
}

const initPatient: Patient = {
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0
}
const patient = ref<Patient>({ ...initPatient })
//计算属性把复选框的1和0 转换为true和false
const defaultFlag = computed({
  get() {
    return patient.value.defaultFlag === 1 ? true : false
  },
  set(value) {
    patient.value.defaultFlag = value ? 1 : 0
  }
})

const form = ref<FormInstance>()
// 添加或者编辑按钮
const onSubmit = async () => {
  await form.value?.validate()
  // 性别校验 取出身份证倒数第二位,$2之后 1男 0女
  const gender = +patient.value.idCard.slice(-2, -1) % 2
  if (gender !== patient.value.gender) {
    await showConfirmDialog({
      title: '温馨提示',
      message: '填写的性别和身份证号中的不一致\n您确认提交吗?'
    })
    console.log('校验成功')
  }
  // 校验成功以后添加还是编辑
  patient.value.id
    ? await editPatinet(patient.value)
    : await addPatient(patient.value)
  // 添加成功关闭弹窗
  show.value = false
  // 提示
  showSuccessToast(patient.value.id ? '编辑成功' : '添加成功')
  // 刷新页面
  loadList()
}
// 删除按钮
const delPatinet = async () => {
  if (patient.value.id) {
    await showConfirmDialog({
      title: '温馨提示',
      message: `您确定要删除${patient.value.name}患者的信息吗`
    })
    show.value = false
    showSuccessToast('删除成功')
    await delPatient(patient.value.id)
    loadList()
  }
}

// 设置选中效果
const patientId = ref<string>()
const selectedPatient = (item: Patient) => {
  console.log(item)
  // 如果有isChange 或者list里面有值
  if (isChange.value && list.value.length) {
    patientId.value = item.id
  }
}

const store = useConsultStore()
const next = () => {
  //判断有没有选中患者 没有就提示
  if (!patientId.value) return showToast('请就诊患者')
  //把患者信息存入到本地
  store.setPatient(patientId.value)
  // 跳转到待支付页面
  router.push('/consult/pay')
}

//获取路由地址
const route = useRoute()
// 是否是选择患者
const isChange = computed(() => route.query.isChange === '1')
// 设置默认选中的ID，当你是选择患者的时候，且有患者信息的时候
</script>

<template>
  <div class="patient-page">
    <!-- 头部提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>

    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'"></cp-nav-bar>
    <div class="patient-list">
      <div
        class="patient-item"
        v-for="item in list"
        :key="item.id"
        @click="selectedPatient(item)"
        :class="{ selected: patientId === item.id }"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <span class="id">{{
            item.idCard.replace(/^(.{6}).+(.{4})$/, '\$1********\$2')
          }}</span>
          <span>{{ item.genderValue }}</span>
          <span>{{ item.age }}岁</span>
        </div>
        <div class="icon">
          <cp-icon name="user-edit" @click="showPopup(item)" />
        </div>
        <div class="tag" v-if="item.defaultFlag === 1">默认</div>
      </div>
      <div class="patient-add">
        <cp-icon name="user-add" @click="showPopup" />
        <p>添加患者</p>
      </div>

      <!-- 底部按钮 -->
      <div class="patient-next" v-if="isChange">
        <van-button type="primary" round block @click="next">下一步</van-button>
      </div>
      <div class="patient-tip" v-if="list.length > 6">最多可添加 6 人</div>
      <!-- 侧边栏 -->
      <van-popup v-model:show="show" position="right">
        <cp-nav-bar
          title="添加患者"
          right-text="保存"
          :back="() => (show = false)"
          @click-right="onSubmit"
        >
        </cp-nav-bar>
        <van-form autocomplete="off" ref="form">
          <van-field label="身份证号" placeholder="请输入身份证号" />
          <van-field
            label="身份证号"
            placeholder="请输入身份证号"
            v-model="patient.idCard"
            :rules="idCardRule"
          />
          <van-field
            label="真实姓名"
            placeholder="请输入真实姓名"
            v-model="patient.name"
            :rules="nameRules"
          />
          <van-field label="性别" class="pb4">
            <!-- 单选按钮组件 -->
            <template #input>
              <cp-radio-btn
                :options="options"
                v-model="patient.gender"
              ></cp-radio-btn>
            </template>
          </van-field>
          <van-field label="默认就诊人">
            <template #input>
              <van-checkbox :icon-size="18" round v-model="defaultFlag" />
            </template>
          </van-field>
        </van-form>
        <van-action-bar v-if="patient.id">
          <van-action-bar-button @click="delPatinet"
            >删除</van-action-bar-button
          >
        </van-action-bar>
      </van-popup>
    </div>
    <!-- 

       :modelValue="gender"
      @update:model-value="gender = $event"

     -->
  </div>
</template>

<style lang="scss" scoped>
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}

// 底部操作栏
.van-action-bar {
  padding: 0 10px;
  margin-bottom: 10px;
  .van-button {
    color: var(--cp-price);
    background-color: var(--cp-bg);
  }
}
.patient-page {
  padding: 46px 0 80px;
  :deep() {
    .van-popup {
      width: 100%;
      height: 100%;
    }
  }
}
.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
.pb4 {
  padding-bottom: 4px;
}
</style>
